package com.example.demo.config;

import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.logging.Logger;


@Configuration
public class CORSConf {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            //配置虚拟路径和实体路径的映射关系
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/images/**").
                        addResourceLocations("file:D:/file/");
                registry.addResourceHandler("/downloads/**").
                        addResourceLocations("file:D:/download/");
            }
            //添加拦截代码
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new MyInterceptor())//添加自定义拦截器
                        .addPathPatterns("/**/**")//拦截所有的请求路径接口
                        .excludePathPatterns("/noLogin/**")//表示放行请求路径中带有noLogin，
                        .excludePathPatterns("/detail");//表示放行请求路径中带有detail，
            }

            /**
             * 设置跨域，让前端允许访问后台的接口
             */
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*");
            }
        };
    }
}